<template>
	<div class="permission-edit-container" v-loading="loading">
		<!-- 主内容区 -->
		<div class="main-content">
			<!-- 左侧表单区域 -->
			<div class="form-container">
				<h2 class="section-title">修改角色权限</h2>

				<el-form ref="formRef" :model="form" label-position="top" label-width="120px">
					<!-- 角色信息 -->
					<el-form-item label="角色ID" prop="roleId">
						<el-input v-model="form.roleId" disabled />
					</el-form-item>

					<el-form-item label="角色名称" prop="roleName">
						<el-input v-model="form.roleName" disabled />
					</el-form-item>

					<!-- 权限选择 -->
					<el-form-item label="权限设置" prop="permissions">
						<el-checkbox-group v-model="form.selectedPermissions" class="permission-group">
							<div v-for="(permGroup, groupKey) in groupedPermissions" :key="groupKey"
								class="permission-category">
								<h3 class="category-title">{{ getCategoryName(groupKey) }}</h3>
								<el-checkbox v-for="perm in permGroup" :key="perm.id" :label="perm.id"
									class="permission-item">
									<div class="perm-content">
										<span class="perm-code">{{ perm.permCode }}</span>
										<span class="perm-name">{{ perm.permName }}</span>
										<el-tooltip effect="dark" :content="perm.description" placement="top">
											<el-icon>
												<InfoFilled />
											</el-icon>
										</el-tooltip>
									</div>
								</el-checkbox>
							</div>
						</el-checkbox-group>
					</el-form-item>
				</el-form>
			</div>

			<!-- 右侧预览区域 -->
			<div class="preview-container">
				<h2 class="section-title">权限变更预览</h2>

				<div class="preview-details">
					<h3>角色信息</h3>
					<ul>
						<li><el-icon>
								<User />
							</el-icon> 角色ID: {{ form.roleId || "未设置" }}</li>
						<li><el-icon>
								<User />
							</el-icon> 角色名称: {{ form.roleName || "未设置" }}</li>
					</ul>

					<div class="permission-change">
						<h4>权限变更</h4>
						<div class="change-summary">
							<div class="added-perms" v-if="addedPermissions.length > 0">
								<h5>新增权限</h5>
								<ul>
									<li v-for="perm in addedPermissions" :key="perm.id">
										<el-icon>
											<CirclePlus />
										</el-icon>
										{{ perm.permName }} ({{ perm.permCode }})
									</li>
								</ul>
							</div>
							<div class="removed-perms" v-if="removedPermissions.length > 0">
								<h5>移除权限</h5>
								<ul>
									<li v-for="perm in removedPermissions" :key="perm.id">
										<el-icon>
											<Remove />
										</el-icon>
										{{ perm.permName }} ({{ perm.permCode }})
									</li>
								</ul>
							</div>
							<div v-if="addedPermissions.length === 0 && removedPermissions.length === 0">
								<p>无权限变更</p>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 底部操作栏 -->
		<div class="bottom-bar">
			<el-button @click="handleCancel">返回</el-button>
			<div class="right-buttons">
				<el-button type="primary" @click="handleSubmit">确认修改</el-button>
			</div>
		</div>
	</div>
</template>

<script>
	export default {
		name: 'RolePermissionEditView',
	};
</script>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from "vue";
	import {
		useRoute,
		useRouter
	} from 'vue-router'
	import {
		User,
		InfoFilled,
		CirclePlus,
		Remove
	} from '@element-plus/icons-vue'
	import {
		ElMessage,
		ElMessageBox
	} from "element-plus";
	import {
		getRoleDetail
	} from '@/api/role.js'
	import {
		grantPermission,
		revokePermission,
		getAllPermission
	} from '@/api/permission.js'

	const router = useRouter()
	const route = useRoute()
	const roleId = route.params.id // 角色ID
	const loading = ref(false)

	/**
	 * 表单数据
	 */
	const form = ref({
		roleId: "",
		roleName: "",
		currentPermissions: [],
		selectedPermissions: []
	});

	/**
	 * 权限列表
	 */
	const allPermissions = ref([]);

	/**
	 * 按权限代码首字母分组权限
	 */
	const groupedPermissions = computed(() => {
		const groups = {};
		allPermissions.value.forEach(perm => {
			const groupKey = perm.permCode.charAt(0);
			if (!groups[groupKey]) {
				groups[groupKey] = [];
			}
			groups[groupKey].push(perm);
		});
		return groups;
	});

	/**
	 * 获取分类名称
	 */
	const getCategoryName = (groupKey) => {
		const categoryMap = {
			'A': '预约管理',
			'B': '员工管理',
			'C': '顾客服务',
			'D': '财务管理',
			'E': '系统管理',
			'H': '测试权限'
		};
		return categoryMap[groupKey] || `其他权限 (${groupKey})`;
	};

	/**
	 * 新增的权限
	 */
	const addedPermissions = computed(() => {
		return allPermissions.value.filter(perm =>
			form.value.selectedPermissions.includes(perm.id) &&
			!form.value.currentPermissions.includes(perm.id)
		);
	});

	/**
	 * 移除的权限
	 */
	const removedPermissions = computed(() => {
		return allPermissions.value.filter(perm =>
			!form.value.selectedPermissions.includes(perm.id) &&
			form.value.currentPermissions.includes(perm.id)
		);
	});

	/**
	 * 获取角色信息和权限列表
	 */
	const fetchData = async () => {
		loading.value = true;
		try {
			// 获取所有权限
			const permsRes = await getAllPermission();
			if (permsRes.code === 200) {
				allPermissions.value = permsRes.data;
			}

			// 获取角色详情
			const roleRes = await getRoleDetail(roleId);
			if (roleRes.code === 200) {
				form.value.roleId = roleRes.data.id;
				form.value.roleName = roleRes.data.roleName;
				// 将角色已有的权限ID提取出来
				form.value.currentPermissions = roleRes.data.permissions ?
					roleRes.data.permissions.map(p => p.id) :
					[];
				// 默认选中当前权限（这里确保使用权限ID数组）
				form.value.selectedPermissions = [...form.value.currentPermissions];
			}
		} catch (error) {
			ElMessage.error('获取数据失败');
		} finally {
			loading.value = false;
		}
	};

	/**
	 * 提交修改
	 */
	const handleSubmit = async () => {
		try {
			// 检查是否有变更
			if (addedPermissions.value.length === 0 && removedPermissions.value.length === 0) {
				ElMessage.warning('没有权限变更');
				return;
			}

			// 确认对话框
			await ElMessageBox.confirm(
				`确定要修改角色【${form.value.roleName}】的权限吗？`,
				'确认修改', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}
			);

			loading.value = true;

			// 处理新增权限
			const grantPromises = addedPermissions.value.map(perm =>
				grantPermission(perm.id)
			);

			// 处理移除权限
			const revokePromises = removedPermissions.value.map(perm =>
				revokePermission(perm.id)
			);

			// 并行执行所有权限变更请求
			const results = await Promise.allSettled([...grantPromises, ...revokePromises]);

			// 检查结果
			const hasError = results.some(result => result.status === 'rejected');
			if (hasError) {
				ElMessage.error('部分权限修改失败');
			} else {
				ElMessage.success('权限修改成功');
				fetchData(); // 重新加载数据
			}
		} catch (error) {
			if (error !== 'cancel') {
				console.error('提交失败:', error);
				ElMessage.error(`操作失败: ${error.message || '未知错误'}`);
			}
		} finally {
			loading.value = false;
		}
	};

	/**
	 * 取消编辑
	 */
	const handleCancel = () => {
		ElMessageBox.confirm("确定放弃当前编辑的内容吗？", "提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning",
			})
			.then(() => {
				ElMessage.info("已取消编辑");
				router.back();
			})
			.catch(() => {});
	};

	const formRef = ref(null);

	onMounted(() => {
		if (roleId) {
			fetchData();
		} else {
			ElMessage.error('无效的角色ID');
			router.back();
		}
	});
</script>

<style scoped>
	.permission-edit-container {
		min-height: 100vh;
		background-color: #f9fafb;
		padding: 20px;
		height: 95%;
		min-height: 0;
		overflow-y: auto;
	}

	.section-title {
		font-size: 1.25rem;
		font-weight: 600;
		margin-bottom: 1.5rem;
	}

	.main-content {
		display: flex;
		gap: 20px;
		flex-wrap: wrap;
	}

	.form-container {
		flex: 1;
		min-width: 400px;
		background-color: white;
		padding: 20px;
		border-radius: 4px;
		box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
	}

	.preview-container {
		flex: 1;
		min-width: 300px;
		background-color: white;
		padding: 20px;
		border-radius: 4px;
		box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
		position: sticky;
		top: 20px;
	}

	.bottom-bar {
		margin-top: 20px;
		padding: 15px 20px;
		background-color: white;
		box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.right-buttons {
		display: flex;
		gap: 10px;
	}

	.preview-details h3 {
		font-size: 1.1rem;
		font-weight: 600;
		margin-bottom: 1rem;
	}

	.preview-details ul {
		list-style: none;
		padding: 0;
		margin-bottom: 1.5rem;
	}

	.preview-details li {
		margin-bottom: 0.75rem;
		color: #6b7280;
		display: flex;
		align-items: center;
		gap: 8px;
	}

	.permission-group {
		display: flex;
		flex-direction: column;
		gap: 15px;
	}

	.permission-category {
		border: 1px solid #e5e7eb;
		border-radius: 6px;
		padding: 10px 15px;
		background-color: #f9fafb;
	}

	.category-title {
		font-size: 0.95rem;
		font-weight: 600;
		color: #374151;
		margin-bottom: 10px;
		padding-bottom: 5px;
		border-bottom: 1px dashed #d1d5db;
	}

	.permission-item {
		margin: 8px 0;
	}

	.perm-content {
		display: flex;
		align-items: center;
		gap: 10px;
	}

	.perm-code {
		font-family: monospace;
		font-weight: bold;
		color: #3b82f6;
		min-width: 30px;
	}

	.perm-name {
		flex: 1;
	}

	.permission-change {
		margin-top: 20px;
	}

	.change-summary {
		margin-top: 10px;
		padding: 10px;
		background-color: #f3f4f6;
		border-radius: 4px;
	}

	.added-perms h5,
	.removed-perms h5 {
		font-size: 0.875rem;
		font-weight: 500;
		margin: 5px 0;
	}

	.added-perms li {
		color: #67c23a;
	}

	.removed-perms li {
		color: #f56c6c;
	}

	.added-perms li,
	.removed-perms li {
		display: flex;
		align-items: center;
		gap: 5px;
		margin: 5px 0;
	}
</style>